export const textElement = 'textElement'
export const eventHandlerReg = /^on(.*)/
export const toLowerCaseEventHandler = (event) => {
  return event.replace(eventHandlerReg, (...e) => e[1].toLowerCase())
}
export const useIdeFiber = (tree) => {
  const runtask = (fiber) => {
    let { nodeType, props, dom } = fiber
    if (!dom) {
      dom = fiber.dom =
        nodeType === textElement
          ? document.createTextNode('')
          : document.createElement(nodeType)
      props &&
        Object.keys(props).forEach((key) => {
          if (key !== 'children') {
            if (eventHandlerReg.test(key)) {
              dom.addEventListener(toLowerCaseEventHandler(key), props[key])
            } else {
              dom[key] = props[key]
            }
          }
        })
      fiber.parent.dom.appendChild(dom)
    }
  }
  let nextFiber = tree
  const runFiber = (fiber) => {
    runtask(fiber)
    let preChild = null
    console.log(99, fiber)
    fiber.props &&
      fiber.props.children.forEach((child, index) => {
        child.parent = fiber
        if (index === 0) {
          fiber.nextFiber = child
        } else {
          preChild.sibling = child
        }
        preChild = child
      })
    if (fiber.nextFiber) {
      return fiber.nextFiber
    }
    if (fiber.sibling) {
      return fiber.sibling
    }
    return fiber.parent.sibling ? fiber.parent.sibling : ''
  }
  const callBack = (IdleDeadline) => {
    while (IdleDeadline.timeRemaining() > 1 && nextFiber) {
      nextFiber = runFiber(nextFiber)
    }
    nextFiber && requestIdleCallback(callBack)
  }
  requestIdleCallback(callBack)
}
